<?php
class Mozg_AjaxFileUploader
{
	protected $_obj;
	protected $_form;

	public function __construct(Mozg_Property_Params $obj, App_Tpl_Form $form)
	{
		$this->_obj = $obj;
		$this->_form =$form;
	}

	public function Upload()
	{
       	$fieldName = Mozg::Request('http')->getQuery('fieldName');

		$varParts = explode('[', $fieldName);
		foreach ($varParts as &$varPart)
		{
			$varPart = trim($varPart, ']');
		}

		$origVarName = array_shift($varParts);
		$origFieldName = $varParts[1];
		$origGroupName = $varParts[0];

		if (isset($_FILES['qqfile']))
		{
			$postData = $this->CreatePostFileFromPost();
		}
		else
		{
       		$postData = $this->CreatePostFileFromStream();
		}

		$data = $this->CreateDataArray($varParts, $postData);

       	$this->_form->AddPostData($this->_obj, $data);

		$fileData = $this->_obj->{'Get' .$origFieldName}();
		$output = array();
		if (isset($fileData['error']) && $fileData['error'])
		{
			$output['error'] = $fileData['error'];
		}
		else
		{
	    	$params = $this->_form->Form($this->_obj)->GetFieldConfig($origGroupName, $origFieldName);
			$fieldTpl = $this->_form->GetFieldTpl($params['type']);
			$thumbBlock = $fieldTpl->GetThumbnailBlock($fileData['file'], $origVarName. '[' .$origGroupName. '][' .$origFieldName. ']', isset($params['showimgtumb']) ? $params['showimgtumb'] : false);

			$output['success'] = true;
			$output['file'] = $fileData['file'];
			$output['html'] = $thumbBlock;
		}

		//2 parameter supported from PHP 5.3.0
		return Mozg::Lib('Json')->Encode($output, JSON_HEX_TAG | JSON_HEX_AMP);
	}

	protected function CreatePostFileFromPost()
	{
		return Mozg::Request('http')->getPost('qqfile');
	}

    protected function CreatePostFileFromStream()
    {
        $input = fopen("php://input", "r");
        $tempName = tempnam(sys_get_temp_dir(), '');
        $temp = fopen($tempName, "w");
        $realSize = stream_copy_to_stream($input, $temp);
        fseek($temp, 0, SEEK_SET);
        fclose($input);

        $fileSize = isset($_SERVER["CONTENT_LENGTH"]) ? $_SERVER["CONTENT_LENGTH"] : $realSize;

        $error = 0;
		if ($fileSize < $realSize)
		{
			$error = FILE_WAS_UPLOADED_PARTIALLY;
		}
		else if ($fileSize > $realSize)
		{
			$error = UPLOAD_ERR_FORM_SIZE;
		}

		return array(
			'name' => Mozg::Request('http')->getQuery('qqfile'),
			'size' => $realSize,
			'tmp_name' => $tempName,
			'error' => $error,
			'type' => isset($_SERVER["CONTENT_TYPE"]) ? $_SERVER["CONTENT_TYPE"] : 'application/octet-stream',
		);
    }

    protected function CreateDataArray(array $varParts, array $postData)
    {
        $initData = array();

    	$data = &$initData;
		while ($varPart = array_shift($varParts))
		{
			if (!isset($data[$varPart])) $data[$varPart] = array();
			$data = &$data[$varPart];
		}

		$data = $postData;
		return $initData;
    }
}